<template>
  <div class="role-management">
    <div class="page-header">
      <h1 class="page-title">
        <Users :size="24" style="margin-right: 12px;" />
        默认角色管理
      </h1>
      <p class="page-description">管理系统中的默认AI角色配置和设置</p>
    </div>
    
    <div class="content-area">
      <a-card title="默认角色列表" :bordered="false">
        <template #extra>
          <a-space>
            <a-button @click="handleImportRole">
              <Download :size="16" style="margin-right: 4px;" />
              导入角色
            </a-button>
            <a-button type="primary" @click="handleCreateRole">
              <Plus :size="16" style="margin-right: 4px;" />
              创建默认角色
            </a-button>
          </a-space>
        </template>
        
        <a-table 
          :columns="columns" 
          :data-source="roleList" 
          :pagination="{ 
            pageSize: pagination.pageSize,
            current: pagination.current,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }"
          :loading="loading"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'avatar'">
              <a-avatar 
                :size="40" 
                :src="record.avatarUrl || record.avatar"
                :style="{ backgroundColor: '#6366f1' }"
              >
                {{ (record.roleName || 'R')[0] }}
              </a-avatar>
            </template>
            <template v-else-if="column.key === 'category'">
              <a-tag color="blue">{{ getCategoryName(record.category) }}</a-tag>
            </template>
            <template v-else-if="column.key === 'voiceId'">
              <a-tag v-if="record.voiceId" color="purple">
                {{ getVoiceName(record.voiceId) }}
              </a-tag>
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'knowledgeId'">
              <a-tag v-if="record.knowledgeId" color="cyan">
                {{ getKnowledgeName(record.knowledgeId) }}
              </a-tag>
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'createdAt'">
              {{ record.createdAt ? record.createdAt.replace('T', ' ').split('.')[0] : '-' }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-button type="link" size="small" danger @click="handleDelete(record)">
                  删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 弹窗组件 -->
    <DefaultRoleCreateModal
      v-model:open="createModalOpen"
      @success="handleCreateSuccess"
    />
    
    <DefaultRoleEditModal
      v-model:open="editModalOpen"
      :role="currentRole"
      @success="handleEditSuccess"
    />
    
    <DefaultRoleDeleteModal
      v-model:open="deleteModalOpen"
      :role="currentRole"
      @success="handleDeleteSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Users, Plus, Download } from 'lucide-vue-next'
import { message } from 'ant-design-vue'
import roleService, { type ExtendedRole } from '@/api/roleService'
import { useResourceStore } from '@/stores'
import DefaultRoleCreateModal from '@/components/RoleManager/DefaultRoleCreateModal.vue'
import DefaultRoleEditModal from '@/components/RoleManager/DefaultRoleEditModal.vue'
import DefaultRoleDeleteModal from '@/components/RoleManager/DefaultRoleDeleteModal.vue'

// 获取stores
const resourceStore = useResourceStore()

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 180,
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    width: 80,
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
    width: 120,
  },
  {
    title: '描述',
    dataIndex: 'prompt',
    key: 'prompt',
    ellipsis: true,
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 100,
  },
  {
    title: '音色',
    dataIndex: 'voiceId',
    key: 'voiceId',
    width: 120,
  },
  {
    title: '知识库',
    dataIndex: 'knowledgeId',
    key: 'knowledgeId',
    width: 200,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
  },
]

// 响应式数据
const roleList = ref<ExtendedRole[]>([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 弹窗状态
const createModalOpen = ref(false)
const editModalOpen = ref(false)
const deleteModalOpen = ref(false)
const currentRole = ref<ExtendedRole | null>(null)

// 加载默认角色列表
const loadDefaultRoles = async () => {
  try {
    loading.value = true
    
    const response = await roleService.getDefaultRoles({
      pageNo: pagination.value.current,
      pageSize: pagination.value.pageSize
    })
    
    console.log('加载默认角色列表成功:', response)
    
    roleList.value = response.records
    pagination.value.total = response.total
    pagination.value.current = response.current
    pagination.value.pageSize = response.size
  } catch (error) {
    console.error('加载默认角色列表失败:', error)
    message.error('加载默认角色列表失败，请重试')
    roleList.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (paginationInfo: any) => {
  pagination.value.current = paginationInfo.current
  pagination.value.pageSize = paginationInfo.pageSize
  loadDefaultRoles()
}

// 获取分类名称
const getCategoryName = (category: string) => {
  const categoryMap: Record<string, string> = {
    'assistant': '智能助手',
    'entertainment': '娱乐',
    'education': '教育',
    'health': '健康',
    'business': '商务',
    'creative': '创意',
    'default': '默认'
  }
  return categoryMap[category] || category
}

// 获取音色名称
const getVoiceName = (voiceId: string) => {
  return resourceStore.getVoiceName(voiceId)
}

// 获取知识库名称
const getKnowledgeName = (knowledgeId: string) => {
  return resourceStore.getKnowledgeBaseName(knowledgeId)
}

// 处理创建角色
const handleCreateRole = () => {
  createModalOpen.value = true
}

// 处理导入角色
const handleImportRole = () => {
  message.info('导入角色功能开发中...')
}

// 处理查看
const handleView = (record: ExtendedRole) => {
  message.info(`查看角色: ${record.roleName}`)
}

// 处理编辑
const handleEdit = (record: ExtendedRole) => {
  currentRole.value = record
  editModalOpen.value = true
}

// 处理测试
const handleTest = (record: ExtendedRole) => {
  message.info(`测试角色: ${record.roleName}`)
}

// 处理克隆
const handleClone = (record: ExtendedRole) => {
  message.info(`克隆角色: ${record.roleName}`)
}

// 处理删除
const handleDelete = (record: ExtendedRole) => {
  currentRole.value = record
  deleteModalOpen.value = true
}

// 弹窗事件处理
const handleCreateSuccess = async (newRole: ExtendedRole) => {
  try {
    await loadDefaultRoles() // 重新加载角色列表
    message.success('默认角色创建成功！')
  } catch (error) {
    message.warning('默认角色创建成功，但刷新列表失败，请手动刷新页面')
  }
}

const handleEditSuccess = async (updatedRole: ExtendedRole) => {
  try {
    await loadDefaultRoles() // 重新加载角色列表
  } catch (error) {
    message.warning('默认角色更新成功，但刷新列表失败，请手动刷新页面')
  }
}

const handleDeleteSuccess = async (roleId: string) => {
  try {
    await loadDefaultRoles() // 重新加载角色列表
  } catch (error) {
    message.warning('默认角色删除成功，但刷新列表失败，请手动刷新页面')
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 初始化资源数据
  resourceStore.initResource()
  // 加载默认角色列表
  loadDefaultRoles()
})
</script>

<style scoped>
.role-management {
  height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.content-area {
  height: calc(100% - 100px);
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>